<script setup>
import { defineProps, toRef, computed, inject, ref, watch } from 'vue'
import { useStore } from 'vuex'
import useLoop from './hooks/useLoop'

function calcThresholdLevel (value, threshold) {
  if (threshold && threshold.red && value >= threshold.red) {
    return 'red';
  }
  if (threshold && threshold.orange && value >= threshold.orange) {
    return 'orange';
  }
  if (threshold && threshold.green && value >= threshold.green) {
    return 'green';
  }
  return 'green';
}

// 全局的，所有场馆阈值的定义对象
const store = useStore()
const threshold = computed(() => store.state.threshold.data)

// 由其他组件驱动的场馆过滤
const filterValue = inject('filterValue')

// 通过toRef定义的具有响应式的Props.markList
const props = defineProps({
  markList: Array
})
const markListRef = toRef(props, 'markList')

// 全集合的临时值
const fullMarkMap = {}

// 最终渲染的场馆集合
const markMap = ref({})

// 轮播的控制
let { chooseMark, goRun, init, activePointId } = useLoop({ fullMarkMap, filterValue })

/**
 * 依赖多的源
 */
watch([markListRef, threshold, filterValue, activePointId], ([markList, threshold, filter, activeId], []) => {
  const resultMap = {}
  markList.forEach(mark => {
    const { id, value, name } = mark
    if (filter === '' || filter === id) {
      const color = calcThresholdLevel(value, threshold[id])
      const active = id === activeId
      resultMap[id] = {
        id,
        name,
        value,
        color,
        active
      }
    }

    if (filter === '') {
      fullMarkMap[id] = {
        id,
        value,
        name
      }
    }

    if (!init) {
      goRun()
      init = true
    }
  })
  markMap.value = resultMap
}, { deep: true })




</script>

<template>
  <h3>mark count: {{Object.keys(markMap).length}}</h3>
  <a @click="merryGoRound()">继续轮播</a>
  <ul>
    <li v-for="mark in markMap" class="li" @click="chooseMark(mark)">
      <span>{{ mark.name }}</span>
      <span v-bind:style="{color: mark.color}"> - {{ mark.value }}人</span>
      <span v-if="mark.active" class="point" :style="{background: mark.color}"></span>
    </li>
  </ul>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}

.li {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  padding: 4px 18px 4px 6px;
  cursor: pointer;
  width: 500px;
}

.point {
  height: 15px;
  width: 15px;
  background: green;
  border-radius: 50%;
  display: inline-block;
  margin-left: 10px;
}
</style>
